`timescale 1ns / 1ps
/*
 Copyright 2020 Sean Xiao, jxzsxsp@qq.com
 
 Licensed under the Apache License, Version 2.0 (the "License");
 you may not use this file except in compliance with the License.
 You may obtain a copy of the License at
 
 http://www.apache.org/licenses/LICENSE-2.0
 
 Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 */

module csr_minstret     //minstret   -----machine  instruction retire
(
    input sys_clk,

    input i_EXE_vld,

    input i_dbg_mode,
    input i_dbg_stpcyl,

    input [ 11: 0 ] i_csr_addr,
    input [ 31: 0 ] i_csr_val,
    input i_csr_wen,
    
    output reg [ 31: 0 ] o_minstret_l,
    output reg [ 31: 0 ] o_minstret_h,

    input rst_n
);

wire dbg_stop = i_dbg_mode & i_dbg_stpcyl;
always@( posedge sys_clk or negedge rst_n )
if ( !rst_n )
begin
    o_minstret_l <= 32'b0;
    o_minstret_h <= 32'b0;
end
else if ( i_csr_wen )
begin
    case ( i_csr_addr )
        12'hb02: o_minstret_l <= i_csr_val;
        12'hb82: o_minstret_h <= i_csr_val;
        default: ;
    endcase
end
else if ( ( i_EXE_vld ) && ( dbg_stop == 1'b0 ) )
begin
    if ( o_minstret_l == 32'hffff_ffff )
    begin
        o_minstret_l <= 0;
        o_minstret_h <= o_minstret_h + 1;
    end
    else
        o_minstret_l <= o_minstret_l + 1;
end
    
endmodule
